package com.zhang.controller;


import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhang.common.lang.Result;
import com.zhang.entity.Visit;
import com.zhang.service.VisitCountService;
import com.zhang.service.VisitService;
import com.zhang.utils.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张立松
 * @since 2023-05-08
 */
@RestController
@RequestMapping("/visit")
public class VisitController {

    @Autowired
    VisitService visitService;
    @Autowired
    VisitCountService visitCountService;
    @Autowired
    IPUtil ipUtil;

    @RequestMapping("/add")
    Result addVisitRecord(HttpServletRequest request) throws IOException {

        String ip = request.getHeader("x-forwarded-for")!=null?request.getHeader("x-forwarded-for"):request.getRemoteAddr();
        String city = ipUtil.getCityInfo(ip);
        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("user-agent"));     //用户设备标识
        String device = userAgent.getOs().getName()+"，"+userAgent.getBrowser().getName();
        Visit visit = new Visit();
        visit.setIp(ip).setCity(city).setDevice(device).setCreated(LocalDateTime.now());
        //当日访问量+1
        visitCountService.incrVisitCount();
        //本次访问记录存到数据库
        visitService.save(visit);
        //只保留180天内的访问记录，其余删除
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(180L);
        visitService.remove(new UpdateWrapper<Visit>().lt("created",sevenDaysAgo));
        return Result.success("");
    }

}

